import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { Validators, FormBuilder } from '@angular/forms';
import { LuckyTableService } from '../../services/lucky-table.service';
import { AddTableRequest } from '../../models/form';
import { LuckyInfo } from '../../models/lucky-dog';

@Component({
  selector: 'app-add-lucky-table',
  templateUrl: './add-lucky-table.component.html',
  styleUrls: ['./add-lucky-table.component.less']
})
export class AddLuckyTableComponent implements OnInit {
  @Output() closeEvent = new EventEmitter<void>();
  addTableForm = this.fb.group({
    title: ['', Validators.required],
    type: ['number', Validators.required],
    number: [''],
    string: ['']
  });
  constructor(
    private fb: FormBuilder,
    private luckyTableService: LuckyTableService
  ) {}
  ngOnInit(): void {}
  close() {
    this.closeEvent.emit();
  }
  onSubmit() {
    const { title, type, number, string } = this.addTableForm.value;
    const form: AddTableRequest = { title, type };
    if (type === 'number') {
      form.number = number;
    } else {
      form.string = [
        ...new Set<string>(string.split(',').filter(a => a !== ''))
      ];
    }
    this.luckyTableService.add(form, () => this.close());
  }
}
